package com.begye.smartloan.apptest.renzheng.selfie.views

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import kotlin.math.max

class RenZhengSelfieResult : AppCompatImageView {

    private val linePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.parseColor("#5277D6")
        strokeWidth = 4F.dpToPx()
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.ROUND
        strokeJoin = Paint.Join.ROUND
    }
    private val cornerPaint = Paint().apply {
        color = Color.parseColor("#5277D6")
    }
    private val path = Path()

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context!!,
        attrs,
        defStyleAttr,
    )

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        val margin = 2F.dpToPx()
        // 画圆角
        val radius = max(width, height) / 2
        val rect = RectF(0F, 0F, width.toFloat(), height.toFloat())
        path.addRoundRect(rect, radius.toFloat(), radius.toFloat(), Path.Direction.CW)
        canvas.drawPath(path, cornerPaint)
        canvas.clipPath(path)

        super.onDraw(canvas)

        // 画圆环
        canvas.drawArc(
            margin,
            margin,
            width.toFloat() - margin,
            height.toFloat() - margin,
            0F,
            360F,
            false,
            linePaint
        )
    }

    // 将 dp 转换为像素
    private fun Float.dpToPx(): Float {
        return this * context.resources.displayMetrics.density
    }
}